<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="/css/bootstrap-duallistbox.min.css">
<script src="/js/jquery.bootstrap-duallistbox.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#myModal').on("shown.bs.modal",function(e){
            var btn = $(e.relatedTarget),
            campid = btn.data('campid');
            selected_students = btn.data('students');
            // console.log(selected_students);
            $('#campid').val(campid);
            var selectElement = "#students";
            var requestUrl = "get_camp_stus/"+campid;
            var reqeustParams = "";//有参数用json格式
            var selectedDataStr = selected_students.toString();//选中的option（用过英文逗号隔开；新增时，无选中option）
            //初始化
            // console.log(selectedDataStr);
            initListBox(requestUrl, reqeustParams, selectElement, 'id', 'text', selectedDataStr);
        });
    });
    
    /** 
     * 初始化duallistbox
     * reqeustParams：查询参数
     * selectElement：select元素对应属性
     * optionValue
     * optionText
     * selectedDataStr：选中数据，值以,隔开
     */
    function initListBox(url,reqeustParams,selectElement,optionValue,optionText, selectedDataStr) {
        $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
        $.ajax({
            type: 'POST',//请求方式
            url: url,//地址，就是json文件的请求路径
            data: reqeustParams,//请求参数
            async: true,//是否异步
            success: function (data) {
              var selector = $(selectElement)[0];
              $(data).each(function () {
                var o = document.createElement("option");
                o.value = this[optionValue];
                o.text = this[optionText];
                if ("undefined" != typeof (selectedDataStr) && selectedDataStr != "") {
                  var selectedDataArray = selectedDataStr.split(',');
                  $.each(selectedDataArray, function (i, val) {
                    if (o.value == val) {
                      o.selected = 'selected';
                      return false;
                    }
                  });
                }
                if(typeof(selector) != "undefined") {
                    selector.options.add(o);
                }
              });
              
              //渲染dualListbox
                $(selectElement).bootstrapDualListbox({
                    nonSelectedListLabel: '可选学生清单',//未选中list的label，默认false；
                    selectedListLabel: '已选学生清单',//已选中list的label，默认false；
                    showFilterInputs: true,//是否显示过滤的input输入框，默认true显示；为false则过滤相关的内容不起作用、不显示；
                    filterTextClear: '清空过滤条件',//清空过滤条件按钮的文本，默认'show all'，可替换为其他文本；
                    filterPlaceHolder: '过滤条件',//过滤条件input框的placeholder，可自定义内容，默认为'Filter',
                    nonSelectedFilter: '',//未选中option的过滤条件，默认为空字符串 '' ，也可用正则方式，例如：'ion ([7-9]|[1][0-2])' 过滤7、8、9、10、11、12；
                    selectedFilter: '',//已选中option的过滤条件，默认为空字符串 ''；参考：nonSelectedFilter；一般不设置已选中的过滤条件，会导致某些选中的项不在已选中option的过滤条件范围内，无法显示；
                    moveOnSelect: true,//是否移动选中的option；为false时，moveSelected和removeSelected的按钮显示、生效；默认为true；为true只能光标连续选取，松开鼠标，选中的项会移动；为false则可配合键盘的Ctrl和Shift使用，点击moveSelectedLabel和removeSelectedLabel的按钮，option才会移动；
                    moveAllLabel: '添加全部',//添加全部option按钮的label，默认'Move all'
                    moveSelectedLabel: '添加选中',//添加选中option按钮的label，默认'Move selected'
                    removeAllLabel: '移除全部',//移除全部option按钮的label，默认'Remove all'
                    removeSelectedLabel: '移除选中',//移除选中option按钮的label，默认'Remove selected'
                    preserveSelectionOnMove: 'moved',//'moved'或'all'时，展示移动到target列表中的元素（背景色显示），默认false，不展示；没看到'moved'和'all'的区别；
                    helperSelectNamePostfix: '_ast',//为selector的name的后缀为'_helper'，未选中的list后面拼接1，已选中的拼接2；也可通过setHelperSelectNamePostfix(value, refresh)方法修改；
                    selectorMinimalHeight: 260,//selector的最小height，大概小于260px时，为默认值固定高度，更大值则selector高度会增大；不知道默认值的的大小及height的单位
                    infoText: '共 {0} 项',//不过滤时，选中/未选中option共几项；默认为'Showing all {0}'；
                    infoTextFiltered: '从 {1} 项 筛选 {0} 项',//过滤信息，默认'<span class="label label-warning">Filtered</span> {0} from {1}'。从m项中筛选n项；
                    infoTextEmpty: '空',//当筛选条件为 '' ，且选中/未选中列表无option时显示的内容；默认为'Empty list'；
                    filterOnValues: false,//暂时不知具体作用
                });
            },
            error: function (e) {
                // alert(e.msg);
            }
        });
    }
</script>

<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" id="remove"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <input type="hidden" name="campid" id="campid">
                    <fieldset>
                        <div class="control-group">
                            <div class="controls">
                                <select multiple="multiple" name="students" id="students" class="students"></select>
                            </div>
                        </div>
                    </fieldset>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="btn_close" class="btn btn-default"  data-dismiss="modal">关闭</button>
                <button type="button" id="btn_submit" class="btn btn-primary">保存</button>
            </div>
            <input type="text" id="click_position" style="display:none"/>
        </div>
    </div>
</div>

<script type="text/javascript">
    $('#remove').click(function(){
        $('#myModal').modal('hide');
        window.location.href='/admin/small_camp_config';
    });
    $('#btn_close').click(function(){
        $('#myModal').modal('hide');
        window.location.href='/admin/small_camp_config';
    });
     //保存
    $('#btn_submit').click(function(){
        var students = $('#students').val();
        console.log(students);
        var campid = $('#campid').val();
        if (!students) {
            rc.msg.alert("请至少选择一个学生！！","提示信息");
        }else if(students.length>70){
            rc.msg.alert("不能超过70人，请检查！！","提示信息");
        }else{
            $.ajaxSetup({headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}});
            $.ajax({
                url:'save_camp_students',
                data:{camp_id:campid,students:students},
                cache:false,
                async:true,
                type:'POST',
                success:function($result){
                    rc.msg.alert("操作成功！","提示信息",function(){
                        $('#myModal').modal('hide');
                        window.location.href='/admin/small_camp_config';
                    });
                },
            }); 
        }
        // console.log($('#students').val());
    });
    var rc = window.rc || {};
    rc.msg = {
        alert: function(message, title, callback) {
            if (title == null) title = "提示信息";
            rc.msg._show(title,
                message,
                null,
                "alert",
                function(result) {
                    if (callback) callback(result);
                });
        },
        confirm: function(message,title, callback) {
            if (title == null) title = "操作确认";
            rc.msg._show(title,
                message,
                null,
                "confirm",
                function(result) {
                    if (callback) callback(result);
                });
        },
        _show: function(title, msg, value, type, callback) {
            var html = "";
            html += '<div id="mb_box"></div><div id="mb_con"><span id="mb_tit">' + title + "</span>";
            html += '<div id="mb_msg">' + msg + '</div><div id="mb_btnbox">';
            if (type == "alert") {
                html += '<input id="mb_btn_ok" type="button" value="确定" />';
            }
            if (type == "confirm") {
                html += '<input id="mb_btn_no" type="button" value="取消" />';
                html += '<input id="mb_btn_ok" type="button" value="确定" />';
            }
            html += "</div></div>";
     
            //必须先将_html添加到body，再设置Css样式  
            $("body").append(html);
            rc.msg.initCss();
     
            switch (type) {
            case "alert":
                $("#mb_btn_ok").click(function() {
                    rc.msg._hide();
                    callback(true);
                });
                $("#mb_btn_ok").focus().keypress(function(e) {
                    if (e.keyCode == 13 || e.keyCode == 27) {
                        $("#mb_btn_ok").trigger("click");
                    }
                });
                break;
            case "confirm":
                $("#mb_btn_ok").click(function() {
                    rc.msg._hide();
                    if (callback) callback(true);
                });
                $("#mb_btn_no").click(function() {
                    rc.msg._hide();
                    if (callback) callback(false);
                });
                $("#mb_btn_no").focus();
                $("#mb_btn_ok, #mb_btn_no").keypress(function(e) {
                    if (e.keyCode == 13) $("#mb_btn_ok").trigger("click");
                    if (e.keyCode == 27) $("#mb_btn_no").trigger("click");
                });
                break;
            }
        },
        _hide: function() {
            $("#mb_box,#mb_con").remove();
        },
        initCss: function() {
            $("#mb_box").css({
                width: "100%",
                height: "100%",
                zIndex: "99999",
                position: "fixed",
                filter: "Alpha(opacity=60)",
                backgroundColor: "black",
                top: "0",
                left: "0",
                opacity: "0.6"
            });
     
            $("#mb_con").css({
                zIndex: "999999",
                width: "350px",
                height: "200px",
                position: "fixed",
                backgroundColor: "White",
            });
     
            $("#mb_tit").css({
                display: "block",
                fontSize: "14px",
                color: "#444",
                padding: "10px 15px",
                backgroundColor: "#fff",
                borderRadius: "15px 15px 0 0",
                fontWeight: "bold",
                "border-bottom": "1px solid #ddd"
            });
     
            $("#mb_msg").css({
                padding: "20px",
                lineHeight: "40px",
                textAlign: "center",
                fontSize: "18px",
                color: "#4c4c4c"
            });
     
            $("#mb_ico").css({
                display: "block",
                position: "absolute",
                right: "10px",
                top: "9px",
                border: "1px solid Gray",
                width: "18px",
                height: "18px",
                textAlign: "center",
                lineHeight: "16px",
                cursor: "pointer",
                borderRadius: "12px",
                fontFamily: "微软雅黑"
            });
     
            $("#mb_btnbox").css({ margin: "15px 0px 10px 0", textAlign: "center" });
            $("#mb_btn_ok,#mb_btn_no").css({
                width: "80px",
                height: "30px",
                color: "white",
                border: "none",
                borderRadius: "4px"
            });
            $("#mb_btn_ok").css({ backgroundColor: "#b53131" });
            $("#mb_btn_no").css({ backgroundColor: "gray", marginRight: "40px" });
     
     
            //右上角关闭按钮hover样式  
            $("#mb_ico").hover(function() {$(this).css({ backgroundColor: "Red", color: "White" });},
                function() {$(this).css({ backgroundColor: "#DDD", color: "black" });});
     
            var width = document.documentElement.clientWidth; //屏幕宽  
            var height = document.documentElement.clientHeight; //屏幕高  
     
            var boxWidth = $("#mb_con").width();
            var boxHeight = $("#mb_con").height();
     
            //让提示框居中  
            $("#mb_con").css({ top: (height - boxHeight) / 2 + "px", left: (width - boxWidth) / 2 + "px" });
        }
    };
</script>
